package com.lu.core.auto;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.lu.core.aop.DataPermissionInterceptor;
import com.lu.core.support.DataScopePermissionAbstract;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @program lu-boot-saas
 * @description:
 * @author: zhanglu
 * @create: 2022-09-27 20:15:00
 */
@Slf4j
@Component
public class MybatisPlusInterceptorAutoConfiguration implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        try {
            MybatisPlusInterceptor mybatisPlusInterceptor = applicationContext.getBean(MybatisPlusInterceptor.class);
            if(mybatisPlusInterceptor != null){
                Class<? extends DataScopePermissionAbstract>[] handlers = (Class<? extends DataScopePermissionAbstract>[]) DataScopeProxyAutoConfiguration.enableDataScope.getClassArray("handlers");
                for (Class<? extends DataScopePermissionAbstract> clazz : handlers) {
                    DataPermissionInterceptor interceptor = new DataPermissionInterceptor();
                    interceptor.setDataScopePermissionAbstract(clazz.newInstance());
                    mybatisPlusInterceptor.addInnerInterceptor(interceptor);
                }
            }
        } catch (Exception e) {
            log.error(StrUtil.format("lu-datascope-mybatis-spring-boot-starter MybatisPlusInterceptorAutoConfiguration failed {}", e.getMessage()));
        }
    }

}
